package com.shelpe.services.sinbad.service.rtr;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.shelpe.services.sinbad.dto.BalanceRtrDto;
import com.shelpe.services.sinbad.entity.jpa.User;
import com.shelpe.services.sinbad.entity.mongo.BalanceRtr;
import com.shelpe.services.sinbad.repository.jpa.UserRepository;
import com.shelpe.services.sinbad.repository.mongo.BalanceRtrRepository;
import com.shelpe.services.sinbad.service.simbaproxy.UserClient;
import com.shelpe.services.sinbad.service.simbaproxy.UserClient.GetBalanceResponse;

@Service
public class BalanceService {

	@Autowired
	private UserClient userClient;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private BalanceRtrRepository balanceRtrRepository;

	public BalanceRtrDto findBalance(long userID, Date queryTime, int time) {
		User user = this.userRepository.findOne(userID);
		Assert.notNull(user, "user_not_exist");
		BalanceRtr balance = new BalanceRtr();
		balance.from(user, queryTime, time);
		BalanceRtr existing = this.balanceRtrRepository.findByUserIDAndDateGreaterThan(userID, queryTime);

		BalanceRtrDto dto = new BalanceRtrDto();
		if (existing != null && existing.getBalance() != null) {
			dto.setBalance(existing.getBalance());
		}
		return dto;
	}

	public BalanceRtrDto syncBalance(long userID, int time) {
		User user = this.userRepository.findOne(userID);
		Assert.notNull(user, "user_not_exist");
		GetBalanceResponse balanRes = this.userClient.findBalance(user.getNick());

		BalanceRtrDto dto = new BalanceRtrDto();
		if (balanRes != null && balanRes.getRes() != null) {
			float balance = (float) (Math.round(balanRes.getRes().getBalance() * 100)) / 100;
			dto.setBalance(balance);

			BalanceRtr po = new BalanceRtr();
			po.setBalance(balance);
			po.from(user, new Date(), time);
			this.balanceRtrRepository.save(po);
		} else {
			if (balanRes != null && balanRes.getError() != null) {
				dto.setError(balanRes.getError());
			}
		}

		return dto;
	}
}
